package com.siyue.test1.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyue.test1.Hander.SyncStudentHandler;
import com.siyue.test1.entity.Student;
import com.siyue.test1.mapper.StudentMapper;
import com.siyue.test1.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.*;


@RestController
@Slf4j
public class TestController {

    @Autowired
    private SyncStudentHandler syncStudentHandler;

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentMapper studentMapper;

    @RequestMapping("/get-asyn")
    public String test13() throws InterruptedException {
        Long beginTime = System.currentTimeMillis();
        //接收集合各段的 执行的返回结果
        List<Future<List<Student>>> futureList = new ArrayList<Future<List<Student>>>();
        int studentSize = studentMapper.getStudentSize();
        //多线程批量处理的数量
        int threadSize = 3;
//        int count=400000;
        int endSize = 100000;
        int start = 0;
        int end = 0;
        for (int i = 1; i <= threadSize; i++) {
            end = endSize * i - 1;
            if (i == threadSize) {
                end = studentSize + 1000;
            }
            //每段数据集合并行入库
            futureList.add(syncStudentHandler.syncSelectStudents(start, endSize, i));
            start = end + 1;
        }
        List<Student> studentList = new ArrayList<>();
        studentList = Collections.synchronizedList(studentList);
        //对各个线程段结果进行解析
        for (Future<List<Student>> future : futureList) {
            if (null != future) {
                try {
//                    System.out.println(future.get().size()+",当前数据量");
                    studentList.addAll(future.get());
                    log.info("current thread id =" + Thread.currentThread().getName() + ",result=");
                } catch (InterruptedException | ExecutionException e) {
                    log.info("线程运行异常！");
                }
            } else {
                log.info("线程运行异常！");
            }
        }
        Long endTime = System.currentTimeMillis();
        System.out.println("花费的时间是" + (endTime - beginTime));
        return "花费的时间是" + (endTime - beginTime) + ",学生数组的大小是：" + studentList.size();
    }


    @RequestMapping("/get")
    public String test12() throws InterruptedException {
        Long beginTime = System.currentTimeMillis();
//        List<Student> studentList= studentService.list(new QueryWrapper<Student>().last("limit 0,200000"));
        List<Student> studentList = studentService.list(new QueryWrapper<Student>().last("limit 0,300000"));
        Long endTime = System.currentTimeMillis();
        System.out.println("花费的时间是" + (endTime - beginTime));
        return "花费的时间是" + (endTime - beginTime) + ",学生数据大小为" + studentList.size();
    }


    @RequestMapping("/add-asyn")
    public String test1() throws InterruptedException {
        Long beginTime = System.currentTimeMillis();
        List<Student> students = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            Student student = new Student();
            student.setName(UUID.randomUUID().toString());
            student.setId(UUID.randomUUID().toString());
            student.setAge(18);
//            int randomId= rand.nextInt(3);
            //设置随机到的班级Id
//            student.setClassId(classList.get(randomId));
            students.add(student);
        }

        // 监控子线程数据
        CountDownLatch childMonitor = new CountDownLatch(5);
        //子线程在该对象上等待主线程的通知
        CountDownLatch mainMonitor = new CountDownLatch(1);
        // 主线程收集子线程运行最终结果
        List<Boolean> childResponse = new CopyOnWriteArrayList<>();
        //多线程批量处理的数量
//   int threadSize=5000;
        int threadCount = 5; //使用线程数量
        int endSize = students.size() / threadCount;
        int start = 0;
        int end = 0;
        for (int i = 0; i < threadCount; i++) {
            if (i == (threadCount - 1)) {
                end = students.size();
            } else {
                end = (i + 1) * endSize - 1;
            }
            List<Student> studentList = students.subList(start, end);
            start = end + 1;
            //每段数据集合并行入库
            syncStudentHandler.syncSaveStudents(studentList, childMonitor, mainMonitor, childResponse);
        }
        childMonitor.await(60, TimeUnit.SECONDS);
        System.out.println("主线程执行了");
        mainMonitor.countDown();
        Long endTime = System.currentTimeMillis();
        System.gc();  //通知进行垃圾回收
        return "导入学生数量:" + students.size() + "花费事件" + (endTime - beginTime);
    }


    @RequestMapping("/add")
    public String test2() throws InterruptedException {
        Long beginTime = System.currentTimeMillis();
        List<Student> students = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            Student student = new Student();
            student.setName(UUID.randomUUID().toString());
            student.setId(UUID.randomUUID().toString());
            student.setAge(18);
//            int randomId= rand.nextInt(3);
            //设置随机到的班级Id
//            student.setClassId(classList.get(randomId));
            students.add(student);
        }
        studentMapper.saveStudent(students);
        System.gc();  //通知进行垃圾回收
        Long endTime = System.currentTimeMillis();
        return "导入学生数量:" + students.size() + "花费事件" + (endTime - beginTime);
    }
}
